import { createRouter, createWebHashHistory } from 'vue-router';
import { useGlobalStore } from '@/store/global';
import { useAuthenticationStore } from '@/store/Authentication/Authentication';
import routes from './routes';

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});

function allowRouterToNavigate(
  to: any,
  next: (path?: string) => void,
  currentUserRole: string,
) {
  const authenticationStore = useAuthenticationStore();
  if (
    to.matched.some(
      (record: { meta: { requiresAuth: any } }) => record.meta.requiresAuth,
    )
  ) {
    if (authenticationStore.isLoggedIn) {
      if (to.meta.exclusiveToRoles) {
        // The privilege for the specific router was verified using the
        // exclusiveToRoles roles in the router.
        if (to.meta.exclusiveToRoles.includes(currentUserRole)) {
          next();
        } else {
          next('*');
        }
        return;
      }
      next();
      return;
    }
    next('/login');
  } else {
    next();
  }
}

router.beforeEach((to, from, next) => {
  const globalStore = useGlobalStore();
  const authenticationStore = useAuthenticationStore();
  const currentUserRole = globalStore.userPrivilege as string;
  // condition will get satisfied if user refreshed after login
  if (!currentUserRole && authenticationStore.isLoggedIn) {
    // invoke API call to get the role ID
    const username = localStorage.getItem('storedUsername') as string;
    authenticationStore
      .getUserInfo(username)
      .then((response: { RoleId: string }) => {
        if (response?.RoleId) {
          // set role ID
          globalStore.userPrivilege = response.RoleId;
          // allow the route to continue
          allowRouterToNavigate(to, next, response.RoleId);
        }
      })
      .catch(() => {
        to.path === '/login' ? next() : next('/login');
      });
  } else {
    allowRouterToNavigate(to, next, currentUserRole);
  }
});

export default router;
